package com.sduept.nwld.dataserver.controller.equipment.assessment.statistics;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.primefaces.event.SelectEvent;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.sduept.bigdata.equipment.assessment.dto.RiskLevelCountDTO;
import com.sduept.bigdata.equipment.assessment.dto.SubstationRankingDTO;
import com.sduept.bigdata.equipment.assessment.exception.ParameterException;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionPlan;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionQuestionEquipment;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionStation;
import com.sduept.bigdata.equipment.assessment.service.InspectionPlanService;
import com.sduept.bigdata.equipment.assessment.service.InspectionStationService;
import com.sduept.bigdata.equipment.assessment.service.InspectionStatisticalAnalysisService;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.core.service.StandardDictService;
import com.sduept.utils.DateUtil;
import com.sduept.utils.PingYinUtil;

/**
 * @author huangyu
 * @Date 2019年9月16日
 */
@Named
@ViewScoped
public class InspectionPlanAnalysisController extends AbstractController{

	private static final long serialVersionUID = 2772433574982044148L;
	
	@Autowired
	private InspectionPlanService planService;
	@Autowired
	private InspectionStationService stationService;
	@Autowired
	private InspectionStatisticalAnalysisService analysisService;
	@Autowired
	private StandardDictService dictService;
	
	
	private String startDate;
	private String endDate;
	private String actualStartDate;
	private String actualEndDate;
	/**
	 * 已完成的计划
	 */
	private List<InspectionPlan> finishiPlans;
	private InspectionPlan selectedPlan = new InspectionPlan();
	/**
	 * 制定计划下的所有变电站
	 */
	private Set<InspectionStation> stationsAll;
	/**
	 * 已完成的变电站
	 */
	private Set<InspectionStation> stationsFinished = new HashSet<InspectionStation>();
	
	private List<InspectionStationOrderDTO> dtos = new ArrayList<InspectionStationOrderDTO>();
	
	private String finishRatio = "0";
	
	private List<RiskLevelCountDTO> riskLevelCountDTOs=new ArrayList<>();
	
	private String riskLevelCountStr="";
	
	private List<InspectionQuestionEquipment> inspectionQuestionEquipments=new ArrayList<>();
	
	private String userCode;
	
	@PostConstruct
	public void init() {
		userCode=getCurrentUser().getCode();
		finishiPlans = planService.findAll();
		if(finishiPlans.size()>0) {
			selectedPlan = finishiPlans.get(0);
			getPlanDate(selectedPlan);
			getPlanFinishiRatio();
			genInspectionStationOrderDTO(selectedPlan.getId());
			getRiskLevelCountDTOsByPlan();
		}
	}

	private void getPlanFinishiRatio() {
		try {
			stationsFinished.clear();
			stationsAll = stationService.findByInspectionPlan(selectedPlan.getId());
			for (InspectionStation station : stationsAll) {
				if (2 == station.getStatus()) {
					stationsFinished.add(station);
				}
			}
			DecimalFormat df = new DecimalFormat("#0.0");
			if(0 == stationsAll.size()) {
				finishRatio = "0";
			} else {
				double ratio = stationsFinished.size()*100/stationsAll.size();
				finishRatio = df.format(ratio);
			}
		} catch (ParameterException e) {
			e.printStackTrace();
			addErrorMessage("获取计划的检查站出错");
		}
	}
	
	public void genInspectionStationOrderDTO(String planId) {
		dtos.clear();
		SubstationRankingDTO rankDTO = analysisService.getSubstationRanking(planId);
		Map<Integer, List<InspectionStation>> stationOrderMap = rankDTO.getMap();
		for (Integer order : stationOrderMap.keySet()) {
			List<InspectionStation> stations = stationOrderMap.get(order);
			for (InspectionStation station : stations) {
				InspectionStationOrderDTO dto = new InspectionStationOrderDTO();
				dto.setOrder(order);
				dto.setStation(station);
				dtos.add(dto);
			}
		}
		sort(dtos);
	}
	public void getRiskLevelCountDTOsByPlan() {
		riskLevelCountDTOs.clear();
		riskLevelCountStr="";
		if(selectedPlan!=null) {
			riskLevelCountDTOs=analysisService.getRiskLevelCountDTOByInspectionPlanIdAndUserCode(selectedPlan.getId(),userCode);
			riskLevelCountStr=JSON.toJSONString(riskLevelCountDTOs);
			//计算合计
			if(riskLevelCountDTOs.size()>0) {
				RiskLevelCountDTO totalDTO=new RiskLevelCountDTO();
				totalDTO.setName("总计");
				for (RiskLevelCountDTO dto : riskLevelCountDTOs) {
					totalDTO.setLevelOneCount(totalDTO.getLevelOneCount()+dto.getLevelOneCount());
					totalDTO.setLevelTwoCount(totalDTO.getLevelTwoCount()+dto.getLevelTwoCount());
					totalDTO.setLevelThreeCount(totalDTO.getLevelThreeCount()+dto.getLevelThreeCount());
					totalDTO.setLevelFourCount(totalDTO.getLevelFourCount()+dto.getLevelFourCount());
				}
				totalDTO.setTotalCount(totalDTO.getLevelOneCount()+totalDTO.getLevelTwoCount()+totalDTO.getLevelThreeCount()+totalDTO.getLevelFourCount());
				riskLevelCountDTOs.add(totalDTO);
			}
			
		}
	}

	
	/**
	 * 按照变电站排名进行排序
	 * @param list
	 */
	private void sort(List<InspectionStationOrderDTO> list) {
		Collections.sort(list,new Comparator<InspectionStationOrderDTO>() {

			@Override
			public int compare(InspectionStationOrderDTO o1, InspectionStationOrderDTO o2) {
				return o1.getOrder()-o2.getOrder();
			}
		});
	} 
	
	public class InspectionStationOrderDTO {
		
		private Integer order;
		
		private InspectionStation station;
		
		public InspectionStation getStation() {
			return station;
		}
		
		public void setStation(InspectionStation station) {
			this.station = station;
		}
		
		public Integer getOrder() {
			return order;
		}
		
		public void setOrder(Integer order) {
			this.order = order;
		}
		
	}
	/**
	 * 计划查询下拉列表
	 * @param query
	 * @return
	 */
	public List<InspectionPlan> complateInspectionPlan(String query) {
		List<InspectionPlan> result = new ArrayList<InspectionPlan>();
		for (InspectionPlan plan : finishiPlans) {
			String nameHead = PingYinUtil.getPingYinHeader(plan.getName());
			if (nameHead.toLowerCase().contains(query)) {
				result.add(plan);
			}
		}
		return result;
	}

	/**
	 * 查看的计划变化时，同步修改页面显示的数据
	 * @param event
	 */
	public void changeSelectPlan(SelectEvent event) {
		String planId = (String) event.getObject();
		selectedPlan = planService.findById(planId);
		getPlanFinishiRatio();
		getPlanDate(selectedPlan);
		genInspectionStationOrderDTO(selectedPlan.getId());
		getRiskLevelCountDTOsByPlan();
	}
	
	private void getPlanDate(InspectionPlan plan) {
		startDate = DateUtil.getStringDate(plan.getStartTime(), "yyyy-MM-dd");
		endDate = DateUtil.getStringDate(plan.getEndTime(), "yyyy-MM-dd");
		actualStartDate = DateUtil.getStringDate(plan.getActualStartTime(), "yyyy-MM-dd");
		actualEndDate = DateUtil.getStringDate(plan.getActualEndTime(), "yyyy-MM-dd");
	}
	
	public String getStartDate() {
		return startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public String getActualStartDate() {
		return actualStartDate;
	}

	public String getActualEndDate() {
		return actualEndDate;
	}

	public List<InspectionPlan> getFinishiPlans() {
		return finishiPlans;
	}

	public InspectionPlan getSelectedPlan() {
		return selectedPlan;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public void setActualStartDate(String actualStartDate) {
		this.actualStartDate = actualStartDate;
	}

	public void setActualEndDate(String actualEndDate) {
		this.actualEndDate = actualEndDate;
	}

	public void setFinishiPlans(List<InspectionPlan> finishiPlans) {
		this.finishiPlans = finishiPlans;
	}

	public void setSelectedPlan(InspectionPlan selectedPlan) {
		this.selectedPlan = selectedPlan;
	}

	public List<InspectionStationOrderDTO> getDtos() {
		return dtos;
	}

	public void setDtos(List<InspectionStationOrderDTO> dtos) {
		this.dtos = dtos;
	}

	public String getFinishRatio() {
		return finishRatio;
	}

	public void setFinishRatio(String finishRatio) {
		this.finishRatio = finishRatio;
	}

//	public List<String> getRiskLevel() {
//		return riskLevel;
//	}
//
//	public void setRiskLevel(List<String> riskLevel) {
//		this.riskLevel = riskLevel;
//	}

	public Set<InspectionStation> getStationsAll() {
		return stationsAll;
	}

	public void setStationsAll(Set<InspectionStation> stationsAll) {
		this.stationsAll = stationsAll;
	}

	public Set<InspectionStation> getStationsFinished() {
		return stationsFinished;
	}

	public void setStationsFinished(Set<InspectionStation> stationsFinished) {
		this.stationsFinished = stationsFinished;
	}

	public List<RiskLevelCountDTO> getRiskLevelCountDTOs() {
		return riskLevelCountDTOs;
	}

	public void setRiskLevelCountDTOs(List<RiskLevelCountDTO> riskLevelCountDTOs) {
		this.riskLevelCountDTOs = riskLevelCountDTOs;
	}

	public String getRiskLevelCountStr() {
		return riskLevelCountStr;
	}

	public void setRiskLevelCountStr(String riskLevelCountStr) {
		this.riskLevelCountStr = riskLevelCountStr;
	}

	public List<InspectionQuestionEquipment> getInspectionQuestionEquipments() {
		return inspectionQuestionEquipments;
	}

	public void setInspectionQuestionEquipments(List<InspectionQuestionEquipment> inspectionQuestionEquipments) {
		this.inspectionQuestionEquipments = inspectionQuestionEquipments;
	}

}
